package com.hai.comtroller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.ws.spi.http.HttpContext;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@RestController//只返回字符
@RequestMapping(value = "/file")
public class FileController {
    @RequestMapping(value = "/uploadFile.do", consumes = "application/octet-stream")
    @ResponseBody
    public String fileUpload(@RequestParam(required = false) CommonsMultipartFile file) {
        return filesUpload(file);
    }

    @RequestMapping(value = "/uploadFile2.do")
    @ResponseBody
    public String fileUpload2(@RequestParam("file") CommonsMultipartFile file) {
        return filesUpload(file);
    }

    @RequestMapping("/test.do")
    @ResponseBody
    public String register() {
        System.out.println("RestController ok");
        return "RestController ok";
    }

    private String filesUpload(CommonsMultipartFile file) {
        if (file != null && !file.isEmpty()) {
            long tstart = System.currentTimeMillis();
            System.out.println("recevied file name=" + file.getOriginalFilename() + ",file length=" + file.getSize() + ",start time=" + tstart);
            String path = "F:/fileUpload";
            File destFile = new File(path, new Date().getTime() + file.getOriginalFilename());
            if (!destFile.exists()) {
                destFile.mkdirs();
                try {
                    file.transferTo(destFile);
                    long tend = System.currentTimeMillis();
                    String s = "file:" + file.getOriginalFilename() + " upload success with end time=" + tend + ",time spend=" + (tend - tstart);
                    System.out.println(s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "file upload failed";

            }
        }
        return "file is null";
    }

    @RequestMapping(value = "/uploadFileWithUsername.do", method = RequestMethod.POST)
    @ResponseBody
    private String uploadFileWithUsername(@RequestParam("file") CommonsMultipartFile file, String userName) {
        System.out.println("recevied file name=" + file.getOriginalFilename() + ",file length=" + file.getSize() + ",and userName=" + userName);
        return filesUpload(file);
    }

}
